<?php


namespace App\Excel;

use Illuminate\Support\Facades\File;

class XlsWriter
{
    protected $data;
    protected $titles;
    protected $sheetName = '';
    protected $fileName = '';

    public function __construct($data, $titles)
    {
        $this->data = $data;
        $this->titles = $titles;
    }

    public static function get($data, $titles): XlsWriter
    {
        return new self($data, $titles);
    }

    /**
     * @return string
     */
    public function getSheetName(): string
    {
        return $this->sheetName;
    }

    /**
     * @param string $sheetName
     */
    public function setSheetName(string $sheetName): void
    {
        $this->sheetName = $sheetName;
    }


    /**
     * @param string $fileName
     */
    public function setFileName(string $fileName): void
    {
        $this->fileName = $fileName;
    }



    public function down()
    {

        $tmp = storage_path('app/tmp/export');
        if (!File::exists($tmp)) {
            File::makeDirectory($tmp, 0777, true);
        }
        $config = [
            'path' => $tmp // xlsx文件保存路径
        ];
        $excel = new \Vtiful\Kernel\Excel($config);
        $excel->fileName(uniqid() . '.xlsx', $this->sheetName);
        $format = new \Vtiful\Kernel\Format($excel->getHandle());
        $filePath = $excel->header($this->titles)
            ->data($this->data)
            ->defaultFormat($format
                ->fontColor(\Vtiful\Kernel\Format::COLOR_BLACK)
                ->border(\Vtiful\Kernel\Format::BORDER_THIN)
                ->toResource())
            ->freezePanes(1, 0)
            ->output();
        return response()->download($filePath, $this->getFileName())->deleteFileAfterSend(true);
    }

    /**
     * 获取文件名称
     * @return string
     */
    private function getFileName()
    {
        return $this->fileName . date('Ymd') . '.xlsx';
    }
}